from PySide2.QtCore import Qt, QRect
from PySide2.QtWidgets import QDialog, QTreeWidgetItem, QWidget

import Util
from ExcelData import ExcelData, TableData, IndexType, Platform
import Logger
from UiTreeView import Ui_TreeViewDialog

class TreeViewDialog(QWidget, Ui_TreeViewDialog):
    logger: Logger
    currentTreeShowFile: str = ""
    """当前树正在展示的文件"""


    def __init__(self):
        super(TreeViewDialog, self).__init__()

        self.ui = Ui_TreeViewDialog()
        self.ui.setupUi(self)

        self.logger = Logger.Logger()

    def show(self):
        print("打开definition树形展示UI")
        super(TreeViewDialog, self).show()

    def addTreeItem(self, parent: QTreeWidgetItem, text: str):
        item = QTreeWidgetItem(parent)
        item.setText(0, text)
        parent.addChild(item)
        return item

    def refreshTree(self, table: TableData, senderFrom:QWidget):
        """刷新左边树数据"""
        # 相同文件名则不刷新
        self.ui.treeWidget.clear()
        mainItem = QTreeWidgetItem(None)
        mainItem.setExpanded(True)
        mainItem.setText(0, table.jsonName)  # Sheet名

        tableItem = self.addTreeItem(mainItem, table.sheetName)
        tableItem.setExpanded(True)

        strPlatforms: str = ""
        for val in table.exportLibPlatforms.values():
            platform: Platform = val
            strPlatforms += platform.name + " "
        self.addTreeItem(mainItem, "导出代码平台:  " + strPlatforms)

        md5Item = self.addTreeItem(mainItem, "MD5:" + table.lastMd5)
        verItem = self.addTreeItem(mainItem, "最后版本:" + table.lastVersion)
        if not table.lastExecuteTime is None:
            lastTimeItem = self.addTreeItem(mainItem, "最后更新时间:" + Util.getDateTimeString(table.lastExecuteTime))
        classItem = self.addTreeItem(mainItem, "CLASS:" + table.getClassname())

        self.addTreeItem(tableItem, "导出Json名:  " + table.jsonName)
        self.addTreeItem(tableItem, "数据起始行:  " + str(table.fieldDataRowIndex))
        fieldItem = self.addTreeItem(tableItem, "字段总数:  " + str(len(table.fields)))
        for field in table.fields:
            fieldNameItem: QTreeWidgetItem
            detalStr: str = field.fieldName + " [" + field.fieldType.name + "] " + " -->" + field.fieldKey + ""
            if field.canNotEmpty:
                detalStr = "* " + detalStr
            fieldNameItem = self.addTreeItem(fieldItem, detalStr)
            self.addTreeItem(fieldNameItem, "约束:  " + field.fieldRestrain)
        loadCfgItem = self.addTreeItem(tableItem, "加载配置:" + str(len(table.loadConfigs)))
        for config in table.loadConfigs:
            # 加载平台与主键
            detail: str = ""
            strMultKey: str = ""
            for mk in config.keyFields:
                strMultKey += mk.fieldKey + ", "
            strMultKey = strMultKey.strip(", ")
            if config.type is IndexType.List:
                detail = " -> 主键/非空列[" + strMultKey + "]"
            else:
                detail = " -> 主键[" + strMultKey + "]"
            loadCfgItemDetail = self.addTreeItem(loadCfgItem, "" + config.type.name + detail)
            strPlatforms: str = ""
            for val in config.exportPlatforms.values():
                platform: Platform = val
                strPlatforms += platform.name + " "
            self.addTreeItem(loadCfgItemDetail, "导出数据:  " + strPlatforms)
            self.addTreeItem(loadCfgItemDetail, "组别：" + config.group)
            if len(config.loadRelations) > 0:
                loadCfgRelation = self.addTreeItem(loadCfgItemDetail, "关联加载：" + str(len(config.loadRelations)))
                strRelation: str = ""
                for realation in config.loadRelations:
                    self.addTreeItem(loadCfgRelation, realation)
            # 加载字段关联
            if len(config.unions) > 0:
                unionItem = self.addTreeItem(loadCfgItem, "字段关联:    " + str(len(config.unions)))
                for union in config.unions:
                    self.addTreeItem(unionItem, union.myKey + " >> " + union.unionTableName + "->" + union.unionKey)

        # 把梳理出来的树添加到根节点
        self.ui.treeWidget.insertTopLevelItems(0, [mainItem])
        mainItem.setExpanded(True)  # 展开第一个节点
        # self.ui.treeWidget.expandAll() #展开所有节点
        self.resetFormPosition(senderFrom)

    def resetFormPosition(self, senderFrom:QWidget):
        # 调整窗口位置，不阻挡logs
        # screen:QRect = Util.getScreenRect()
        # main:QRect = Util.mainForm.geometry()
        # size:QRect = self.geometry()
        if (not self.isVisible()) and self.isHidden():
            Util.setToTop(self)
        self.move(Util.mainForm.x() - self.width() - 5, Util.mainForm.y())
        self.setFixedHeight(senderFrom.height())



    # def refreshTree(self, data: ExcelData, isForceRefresh: bool = False):
    #     """刷新左边树数据"""
    #     # 相同文件名则不刷新
    #     if self.currentTreeShowFile == data.fileName and isForceRefresh is False:
    #         return
    #     self.ui.treeWidget.clear()
    #     mainItem = QTreeWidgetItem(None)
    #     mainItem.setText(0, data.fileName)  # Sheet名
    #     for tb in data.tables.values():
    #         table: TableData = tb
    #         tableItem = self.addTreeItem(mainItem, table.sheetName)
    #         self.addTreeItem(tableItem, "导出Json名:  " + table.jsonName)
    #         self.addTreeItem(tableItem, "数据起始行:  " + str(table.fieldDataRowIndex))
    #         fieldItem = self.addTreeItem(tableItem, "字段总数:  " + str(len(table.fields)))
    #         for field in table.fields:
    #             fieldNameItem: QTreeWidgetItem
    #             detalStr: str = field.fieldName + " [" + field.fieldType.name + "] " + " -->" + field.fieldKey + ""
    #             if field.canNotEmpty:
    #                 detalStr = "* " + detalStr
    #             fieldNameItem = self.addTreeItem(fieldItem, detalStr)
    #             self.addTreeItem(fieldNameItem, "约束:  " + field.fieldRestrain)
    #         loadCfgItem = self.addTreeItem(tableItem, "加载配置:" + str(len(table.loadConfigs)))
    #         for config in table.loadConfigs:
    #             # 加载平台与主键
    #             detail: str = ""
    #             strMultKey: str = ""
    #             for mk in config.keyFields:
    #                 strMultKey += mk.fieldKey + ", "
    #             strMultKey = strMultKey.strip(", ")
    #             if config.type is IndexType.List:
    #                 detail = " -> 主键/非空列[" + strMultKey + "]"
    #             else:
    #                 detail = " -> 主键[" + strMultKey + "]"
    #             loadCfgItemDetail = self.addTreeItem(loadCfgItem, "" + config.type.name + detail)
    #             strPlatforms: str = ""
    #             for val in config.exportPlatforms.values():
    #                 platform: Platform = val
    #                 strPlatforms += platform.name + " "
    #             self.addTreeItem(loadCfgItemDetail, "导出代码:  " + strPlatforms)
    #             self.addTreeItem(loadCfgItemDetail, "组别：" + config.group)
    #             if len(config.loadRelations) > 0:
    #                 loadCfgRelation = self.addTreeItem(loadCfgItemDetail, "关联加载：" + str(len(config.loadRelations)))
    #                 strRelation: str = ""
    #                 for realation in config.loadRelations:
    #                     self.addTreeItem(loadCfgRelation, realation)
    #             # 加载字段关联
    #             if len(config.unions) > 0:
    #                 unionItem = self.addTreeItem(loadCfgItem, "字段关联:    " + str(len(config.unions)))
    #                 for union in config.unions:
    #                     self.addTreeItem(unionItem, union.myKey + " >> " + union.unionTableName + "->" + union.unionKey)
    #
    #     # 把梳理出来的树添加到根节点
    #     self.ui.treeWidget.insertTopLevelItems(0, [mainItem])
    #     mainItem.setExpanded(True)  # 展开第一个节点
    #     # self.ui.treeWidget.expandAll() #展开所有节点
    #     self.currentTreeShowFile = data.fileName
